<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category SettingConfigService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/20  11:51
 * +--------------------------------------------------------+
 */

namespace App\Services;

use App\Exceptions\EmptyExceptions;
use App\Models\SettingConfig;
use App\Exceptions\ResponseException;
use App\Models\SettingConfigTab;
use Illuminate\Support\Facades\DB;

class SettingConfigService extends BaseService
{
    protected $setting_config;

    protected $setting_config_tab;

    public function __construct()
    {
        $this->setting_config = new SettingConfig();

        $this->setting_config_tab = new SettingConfigTab();
    }

    /**
     * @param $params
     * @return mixed
     * @Depiction 获取数据
     * @Author hwy
     * @Date  2020/7/2  14:57
     */
    public function getOne($params)
    {
        return $this->setting_config->find($params);
    }

    /**
     * @param $params
     * @return mixed
     * @Depiction 获取数据列表
     * @Author hwy
     * @Date  2020/7/2  14:57
     */
    public function getList($params)
    {
        $query = $this->setting_config->query();
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        if (!empty($params['field']) && !empty($params['order'])) {
            $query = $query->orderBy($params['field'], $params['order']);
        }
        if (!empty($params['title'])) {
            $query = $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        if (!empty($params['setting_config_tab_id'])) {
            $query = $query->where('setting_config_tab_id', $params['setting_config_tab_id']);
        }

        $list = $query->paginate($perPage)->toArray();

        return return_success_msg(ResponseException::REQUEST_SUCCESS_MESSAGE, $list);
    }

    /**
     * @param $params
     * @return mixed
     * @Depiction 添加
     * @Author hwy
     * @Date  2020/7/2  14:58
     */
    public function addData($params)
    {
        $add_data = $params->input();
        empty($params->status) ? $edit_data['status'] = 2 : $params->status;

        try {
            $add = $this->setting_config->create($add_data);
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($add) {
            return return_success_msg(ResponseException::SUCCESS_ADD_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_ADD_MESSAGE);
        }
    }

    /**
     * @param $params
     * @param $id
     * @return array|mixed
     * @Depiction 修改
     * @Author hwy
     * @Date  2020/7/2  14:58
     * @throws EmptyExceptions
     */
    public function editData($params, $id)
    {
        $data = $this->getOne($id);
        if (empty($data)) {
            throw new EmptyExceptions(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }
        $edit_data = $params->input();
        empty($params->status) ? $edit_data['status'] = 2 : $params->status;
        try {
            $edit = $data->update($edit_data);
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }
        if ($edit) {
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }

    }

    /**
     * @param $params
     * @param $id
     * @return mixed
     * @Depiction 单页批量修改
     * @Author hwy
     * @Date  2020/10/10  20:24
     */
    public function editDataByName($params)
    {
        DB::beginTransaction();

        $edit_flag = false;
        foreach ($params->input() as $key => $val) {
            //todo 上传字段暂时先跳过
            if ($key == 'file' || $key == 'file_id' || $key == 'file_name' || $key == 'file_path') {
                continue;
            }
            $edit_flag = false;
            $edit_data = $this->setting_config->where('menu_name', $key)->first();
            if (empty($edit_data)) {
                DB::rollBack();
                return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
            }
            $edit_data->value = $val;
            try {
                $edit = $edit_data->save();
                if ($edit) {
                    $edit_flag = true;
                } else {
                    DB::rollBack();
                }
            } catch (\Exception $e) {
                DB::rollBack();
                return return_error_msg($e->getMessage());
            }
        }

        if ($edit_flag) {
            DB::commit();
            sys_config('all', false);
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }

    }

    /**
     * @param $id
     * @return array
     * @Depiction 删除
     * @Author hwy
     * @Date  2020/7/2  14:58
     */
    public function delData($id)
    {
        $data = $this->getOne($id);
        if (empty($data)) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }
        try {
            $del = $data->delete();
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($del) {
            sys_config('all', false);
            return return_success_msg(ResponseException::SUCCESS_DELETE_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_DELETE_MESSAGE);
        }

    }

    /**
     * @param $id
     * @return array
     * @Depiction 设置状态
     * @Author hwy
     * @Date  2020/7/2  14:58
     */
    public function setStatus($id)
    {
        $data = $this->getOne($id);

        if (empty($data)) {
            return return_error_msg(ResponseException::DATA_NOT_EXIST_MESSAGE);
        }

        if ($data->status == 1) {
            $data->status = 2;
        } else {
            $data->status = 1;
        }
        try {
            $edit = $data->save();
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($edit) {
            sys_config('all', false);
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }

    }

    /**
     * @param $setting_config_tab_id 配置分类id
     * @param int $status 状态 1:显示 2:隐藏
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * @Depiction 获取对应分类的配置字段
     * @Author hwy
     * @Date  2020/10/10  19:30
     */
    public function getAll($setting_config_tab_id, int $status = 1)
    {
        $query = $this->setting_config->query();
        $query = $query->where('setting_config_tab_id', $setting_config_tab_id);
        if ($status == 1) {
            $query->where('status', $status);
        }

        return $query->orderBy('sort', 'desc')->orderBy('id', 'asc')->get();
    }

    /**
     * @param int $type
     * @return array
     * @Depiction 获取所有配置分类
     * @Author hwy
     * @Date  2020/7/10  11:16
     */
    public function getConfigTabAll($type = 0)
    {
        $config_tab_all = $this->setting_config_tab->where('status', 1)->where('type', $type)->get();
        $config_tab = [];
        foreach ($config_tab_all as $k => $v) {
            if (!$v['info']) {
                $config_tab[$k]['value'] = $v['id'];
                $config_tab[$k]['label'] = $v['title'];
                $config_tab[$k]['icon'] = $v['icon'];
                $config_tab[$k]['type'] = $v['type'];
            }
        }

        return $config_tab;
    }

    public function getAllConfig()
    {
        $list = $this->setting_config->get()->pluck('value', 'menu_name') ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }

    public function getConfigValue($menu)
    {
        if (empty($menu) || !($config_one = $this->setting_config->where('menu_name', $menu)->first())) {
            return false;
        }
        return json_decode($config_one['value'], true);
    }

    public function getMore($menus)
    {
        $menus = is_array($menus) ? implode(',', $menus) : $menus;
        $list = $this->setting_config->where('menu_name', 'IN', $menus)->pluck('value', 'menu_name') ?: [];
        foreach ($list as $menu => $value) {
            $list[$menu] = json_decode($value, true);
        }
        return $list;
    }

}
